<template>
	<div>
		<el-button @click="importLocalFile" type="primary" v-if="!disabled" size="mini">选择附件</el-button>
		<div >
			<el-tag style="margin-right: 10px;cursor: pointer;" v-for="(item,key) in !disabled?fileListHttp:fileList" :key="key" @click="showFile(item.src)"
			:closable="!disabled"
			@close="handleRemove(item)"
			>{{item.name}} </el-tag>
		</div>
		<el-dialog :visible.sync="dialogVisible" title="图片预览">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>
	</div>
</template>

<script>
	const {
		dialog,
		app,
		shell
	} = require('@electron/remote')
	import {
		name as pkgName
	} from "../../../../../package.json";
	const path = require('path');
	const appDataPath = app.getPath('appData')
	const appFilePath = path.join(appDataPath, `/${pkgName}`)
	const fs = require('fs');

	export default {
		name: 'upLoadImg',
		components: {},
		props: {
			'maxLength': {}, //总数
			'placeholder': {}, //提示文字
			'fileList': {}, //反显附件列表
			'name': {}, //字段名
			//自动上传
			"autoUpload": {
				default: false,
			},
			type: {
				default: 'img'
			},
			//附件类型
			accept: {
				default: '*'
			},
			//附件传参。
			uploadData: {
				default: {}
			},
			//是否禁用上传
			disabled: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				Config: {
					baseUrl: {
						dev: '123'
					}
				},
				fileListHttp: [],
				headers: {
					Authorization: sessionStorage.getItem('token_permissions')
				},
				url: process.env.VUE_APP_URL,
				dialogImageUrl: null,
				dialogVisible: false,
				fileRawList: [],
				urlList: [],
				funUrl: '/systemAnnex/uploadList',
				iid: null,
				src: null,
				cameraLoading: false,
				filePath:null,
				exportPath: '',
			};
		},
		watch: {
			fileListHttp: {
				handler(a) {
					console.log(a)
					this.fileListHttp = a
				},
				deep: true, // 深度监听

			},
			filePath(e){
				this.filePath = e
			},
			closeBtn(e) {
				this.closeBtn = a
			},
		},
		created() {
		},
		mounted() {
			this.getUserDataPath()
			this.fileListHttp  = this.fileList
		},
		methods: {
			getUserDataPath() {
				// 存放文件路径
				this.exportPath = appFilePath + '/taskFile'

			},
			// 本地文件上传
			importLocalFile() {
				// 弹出文件选择框
				dialog.showOpenDialog({
					properties: ['openFile']
				}).then(result => {
					console.log(`选中的文件：储存地址${this.filePath}`,result);
					const sourcePath = result.filePaths[0]; // 获取选中的文件路径
					const fileName = path.basename(sourcePath); // 获取文件名
					//  需要保存给对象的 相对路径
					this.exportPath = path.join(this.exportPath, this.filePath);
					if (!fs.existsSync(this.exportPath)) {
						fs.mkdirSync(this.exportPath, {
							recursive: true
						});
					}
					const targetFilePath = path.join(this.exportPath, fileName); // 目标文件路径
					// 写入文件到固定路径
					fs.copyFileSync(sourcePath, targetFilePath);

					console.log('文件已保存至:', targetFilePath)

					console.log('文件已保存至:', targetFilePath)
					this.fileListHttp.push({
						src: targetFilePath,
						name: fileName
					})
					this.$emit('uploadOk',this.fileListHttp)
					// }).catch(err => {
					// 	console.log(err);
					// });
				})
			},
			grabimage() {
				this.cameraLoading = true;
				let filePath = this.$store.getters.getSystemData('webCamera')[0].typeCode
				var msg1 = {
					"filepath": `${filePath}\\${this.uploadData.name}_${this.uploadData.fileTypeCode}.jpg`,
					"rotate": "",
					"deskew": "",
					"deskewval": "",
					"camidx": "0",
					"ColorMode": "",
					"quality": "1",
					"bAutoAdjust": "",
					"bIsPrint1to1": "",
					"watermark": {
						"pos": "",
						"content": "",
						"transparency": "",
						"fontsize": "",
						"font": "",
						"color": ""
					}
				};
				this.$axiosaj.post("http://127.0.0.1:38088/video=grabimage", msg1).then(response => {
					console.log(' successfully:', response);
					this.cameraLoading = false;
					this.src = "data:image/png;base64," + response.data.photoBase64;


				})
			},
			uploadCameraFile() {
				let file = this.base64toBlob(this.src, 'file')
				let formdata = new FormData();
				formdata.append("file", file);
				formdata.append("iid", this.uploadData.iid || this.iid);
				formdata.append("fileTypeCode", this.uploadData.fileTypeCode);
				this.$axios.post('/systemAnnex/upload', formdata).then(res => {
					if (res.code == 200) {
						this.src = null
						this.$emit('uploadOk')
					}
				})
			},
			// 将base64转换为blob
			base64toBlob(dataurl) {
				let arr = dataurl.split(","),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				let blob = new Blob([u8arr], {
					type: mime
				})
				return new File([blob], 'webPhoto.jpg')
			},
			setFileList() {
				if (this.fileList && this.fileList.indexOf(',') != -1) {
					let arr = this.fileList.split(',')
					this.fileListHttp = arr.map((v, i) => {
						this.urlList.push(this.Config.baseUrl.dev + v.filePath)
						return {
							name: v.fileName,
							url: this.Config.baseUrl.dev + v.filePath,
							fileId: v.fileId
						}
					})
				} else {
					if (this.fileList && this.fileList.length > 0) {
						this.fileListHttp = this.fileList.map((v, i) => {
							this.urlList.push(this.Config.baseUrl.dev + v.filePath)
							return {
								name: v.fileName,
								url: this.Config.baseUrl.dev + v.filePath,
								fileId: v.fileId
							}
						})
					} else {
						this.fileListHttp = []
					}
				}
			},
			beforeUpload(file, fileList) {

				// return false
			},
			showFile(src){
				console.log(shell)
				shell.openPath(src);
			},
			handleRemove(src) {
			
				// this.fileListHttp = this.fileListHttp.filter(v=>v.name != file.name)
				
				shell.openItem(src)
				// this.$axios.get('/systemAnnex/deleteFile', {
				// 	params: {
				// 		iid: file.fileId
				// 	}
				// }).then(res => {
				// 	if (res.code == 200) {
				// 		this.$emit('uploadOk')
				// 	}
				// })
			},
			handlePreview(file) {

			},
			handleExceed(files, fileList) {
				this.$message.warning(`当前限制选择${this.maxLength}个文件`);
			},
			beforeRemove(file, fileList) {
				return this.$confirm(`确定移除 ${ file.name }？`);
			},
			onChange(file, fileList) {
				if (this.uploadData.iid || this.iid) {
					//有iid 单附件上传
					if (this.autoUpload) {
						this.fileRawList = []
						let formdata = new FormData();
						formdata.append("file", file.raw);
						formdata.append("iid", this.uploadData.iid || this.iid);
						formdata.append("fileTypeCode", this.uploadData.fileTypeCode);
						this.$axios.post('/systemAnnex/upload', formdata).then(res => {
							if (res.code == 200) {
								this.$emit('uploadOk')
							}
						})
					}
				} else {
					//没有根据父页面调用 submitUpload 多附件上传。
					this.fileRawList = fileList
					this.$emit('fileLength', fileList)
				}
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
			submitUpload(iid) {
				// this.$refs.uoload.submit()
				if (this.fileRawList.length > 0) {
					let formdata = new FormData();
					let typeCodes = []
					this.fileRawList.forEach(file => {
						formdata.append("files", file.raw);
						typeCodes.push({
							code: this.uploadData.fileTypeCode,
							name: file.name
						})
					})
					formdata.append("iid", this.uploadData.iid || iid);
					formdata.append("typeCodes", JSON.stringify(typeCodes));
					this.$axios.post(this.funUrl, formdata).then(res => {
						if (res.code == 200) {
							this.$emit('uploadOk')
						}
					})
				}
			}
		}
	};
</script>
<style lang="scss" scoped>
	.img-box {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;

		>div {
			margin: 10px;
		}
	}
</style>